package org.znxs.comfriend.adapters;

import static android.content.ContentValues.TAG;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import org.znxs.comfriend.R;
import org.znxs.comfriend.models.Message;
import org.znxs.comfriend.utils.LoginUser;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int VIEW_TYPE_SENT = 1; // 发送消息类型
    private static final int VIEW_TYPE_RECEIVED = 2; // 接收消息类型

    private Context context;
    private List<Message> messageList; // 消息列表
    private LoginUser loginUser; // 当前登录用户
    private String receiverUserId; // 接收者用户 ID

    public MessageAdapter(Context context, String receiverUserId) {
        this.context = context;
        this.loginUser = LoginUser.getInstance(context);
        this.receiverUserId = receiverUserId;

        // 初始化消息列表
        refreshMessages(receiverUserId);
    }

    /**
     * 刷新消息列表
     */
    public void refreshMessages(String receiverId) {
        messageList = loginUser.getMessages(receiverId);
        Log.d(TAG, "MessageAdapter 当前登录user" + messageList);
        notifyDataSetChanged(); // 通知适配器刷新
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_SENT) {
            // 加载发送消息的布局（右侧）
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_message_send, parent, false);
            return new SentMessageViewHolder(view);
        } else {
            // 加载接收消息的布局（左侧）
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_message_received, parent, false);
            return new ReceivedMessageViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        Message message = messageList.get(position);

        if (holder instanceof SentMessageViewHolder) {
            ((SentMessageViewHolder) holder).bind(message);
        } else if (holder instanceof ReceivedMessageViewHolder) {
            ((ReceivedMessageViewHolder) holder).bind(message);
        }
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }

    @Override
    public int getItemViewType(int position) {
        Message message = messageList.get(position);
        Log.d(TAG, "发送消息id: " + message.getSenderId());
        Log.d(TAG, "当前用户id: " + loginUser.getLoginUser().getId());

        if (loginUser.getLoginUser().getId().equals(message.getSenderId())) {
            return VIEW_TYPE_SENT;
        } else {
            return VIEW_TYPE_RECEIVED;
        }
    }

    // 静态方法：格式化时间戳
    private static String formatTimestamp(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        return sdf.format(new Date(timestamp));
    }

    // 发送消息 ViewHolder
    static class SentMessageViewHolder extends RecyclerView.ViewHolder {
        TextView tvMessage;
        TextView tvTimestamp;

        public SentMessageViewHolder(@NonNull View itemView) {
            super(itemView);
            tvMessage = itemView.findViewById(R.id.tv_message);
            tvTimestamp = itemView.findViewById(R.id.tv_timestamp);
        }

        public void bind(Message message) {
            tvMessage.setText(message.getContent());
            tvTimestamp.setText(formatTimestamp(message.getTimestamp()));
        }
    }

    // 接收消息 ViewHolder
    static class ReceivedMessageViewHolder extends RecyclerView.ViewHolder {
        TextView tvMessage;
        TextView tvTimestamp;

        public ReceivedMessageViewHolder(@NonNull View itemView) {
            super(itemView);
            tvMessage = itemView.findViewById(R.id.tv_message);
            tvTimestamp = itemView.findViewById(R.id.tv_timestamp);
        }

        public void bind(Message message) {
            tvMessage.setText(message.getContent());
            tvTimestamp.setText(formatTimestamp(message.getTimestamp()));
        }
    }

}